import CanvasExt from "./CanvasExt";
import DebugExt from "../base/DebugExt";

/** 公用UI管理方案类型 */
enum UIMgrType_T {
    NONE = 0,		// 默认
    POOL = 1 << 0,	// 启用对象池管理
    REMOVE = 1 << 1,	// 结束从父节点移除
    MUTI = 1 << 2,    // 允许UI同时创建多个
}

export default class GamePublicRes {

    /** 资源列表 */
    private _iconList: Map<string, cc.SpriteFrame> = new Map();
    private _iconLen: Map<string, number> = new Map();
    /** 保存公用图片资源 */
    static addIcons(key: string, list: cc.SpriteFrame[]) {
        DebugExt.log("初始化资源【", key, "】列表, size = ", !list ? 0 : list.length);
        const len = !list ? 0 : list.length;
        if (len == 0) return;
        this.getIns()._iconLen.set(key, len);
        list.forEach((sp: cc.SpriteFrame, index: number) => this.getIns()._iconList.set(key + index, sp));
    }
    /** 获取指定公用资源纹理 */
    static getIcon(key: string, index: number): cc.SpriteFrame {
        return this.getIns()._iconList.get(key + index);
    }
    /** 获取指定公用资源纹理总数 */
    static getIconsLen(key: string): number {
        return this.getIns()._iconLen.get(key) || 0;
    }

    /** 注册单款游戏使用的公用UI */
    static regPublicUIs(pfbList: cc.Prefab[]) {
        if (!pfbList || !pfbList.length) return;
        pfbList.forEach(pfb => {
            if (!pfb || !pfb.isValid) return;
            switch (pfb.name) {
                case 'MessageBox':
                    yy.ui.manager.setMessageBoxPrefab(pfb);
                    break;
                case 'ExitConfirm':
                    this.regPubUI(pfb, yy.UIType.ExitGameConfirm, UIMgrType_T.NONE);
                    break;
                case 'GlobalInfoBar':
                    this.regPubUI(pfb, yy.UIType.User1, UIMgrType_T.NONE, (node: cc.Node, param: yy.UIParam) => {
                        const comp: any = node.getComponent("GlobalInfoBar");
                        // const leftNode: cc.Node = param && param.data ? param.data.leftNode : null;
                        // const rightNode: cc.Node = param && param.data ? param.data.rightNode : null;
                        // const showMenu: boolean = param && param.data ? (param.data.showMenu || false) : false;
                        const eventHelp: () => void = param && param.data ? param.data.eventHelp : undefined;
                        const eventExit: () => void = param && param.data ? param.data.eventExit : undefined;
                        if (!!comp) {
                            // if (!!comp.init)
                            //     comp.init(leftNode, rightNode, showMenu, true);
                            // 第三版信息栏，menu菜单常态显示，根据showMenu参数功能不同
                            if (!!comp.setMenuBtnEvent)
                                comp.setMenuBtnEvent(eventHelp, eventExit);
                        }
                        return true;
                    });
                    break;
            }
        });
    }


    /** 单例 */
    static getIns(): GamePublicRes {
        if (!this._ins)
            this._ins = new GamePublicRes();
        return this._ins;
    }
    private static _ins: GamePublicRes = null;
    private constructor() { }

    /** 销毁 */
    static destory() {
        if (this._ins) {
            delete this._ins;
            this._ins = null;
        }
    }

    // 公共UI对象池列表
    private static _poolList: Map<number, cc.NodePool> = new Map();
    /**
     * 向yycore框架注册公用UI
     * @param pfb 预制体
     * @param uiType 注册公用UI类型
     * @param mgrType 公用UI管理方案类型
     */
    private static regPubUI(pfb: cc.Prefab, uiType: yy.UIType, mgrType: UIMgrType_T,
        initFunc?: (node: cc.Node, param?: yy.UIParam, subType?: any) => boolean) {
        yy.ui.manager.regPulibUI(uiType, (param?: yy.UIParam, subType?: any) => {
            if (!!param && !!param.isHide) {
                this.hideNode(uiType, mgrType);
            }
            else {
                const node: cc.Node = this.addNode(uiType, mgrType, pfb, param);
                if (!node || !node.isValid) return;
                if (!!initFunc && !initFunc(node, param, subType)) return;

                const comp: any = node.getComponent('PublicUIBase');
                if (!!comp) {
                    comp.endRemove = !!(mgrType & UIMgrType_T.REMOVE);
                    if (!!(mgrType & UIMgrType_T.POOL))
                        comp.nodePool = this.getPool(uiType);
                    if (comp.show != undefined)
                        comp.show(param);
                } else {
                    node.active = true;
                }

                // 返回yy.IPublicUI节点对象
                const pui: yy.IPublicUI = {
                    getNode: () => {
                        return node;
                    },
                    getElement: (type?: any): any => {
                        if (param.name == "UserInfoBar" || subType == 4) {
                            const comp: any = node.getComponent("GlobalInfoBar");
                            if (comp)
                                return comp.getElement(type);
                        }
                        return null;
                    }
                };
                return pui;
            }
        });
    }
    // 获取指定对象池
    private static getPool(uiType: yy.UIType): cc.NodePool {
        let pool: cc.NodePool = this._poolList.get(uiType);
        if (!pool) {
            pool = new cc.NodePool();
            this._poolList.set(uiType, pool);
        }
        return pool;
    }
    // 隐藏公用节点
    private static hideNode(uiType: yy.UIType, mType: UIMgrType_T): void {
        DebugExt.debug(`[GlobalUI] 隐藏 UIType.${yy.UIType[uiType]}`);

        const node: cc.Node = CanvasExt.getNode(uiType);
        if (!!node && node.isValid) {
            const comp: any = node.getComponent('PublicUIBase');
            if (!!comp && comp.hide != undefined) {
                comp.hide();
            } else {
                node.active = false;
                if (!!(mType & UIMgrType_T.POOL))
                    this.getPool(uiType).put(node);
            }
        }
    }
    // 添加节点
    private static addNode(uiType: yy.UIType, mType: UIMgrType_T, pfb: cc.Prefab, param?: yy.UIParam): cc.Node {
        DebugExt.debug(`[GlobalUI] 显示 UIType.${yy.UIType[uiType]}`);

        let node: cc.Node = null;
        let parent: cc.Node = !!param ? param.parentNode : null;
        if (!parent || !parent.isValid)
            parent = cc.director.getScene();

        if (!(mType & UIMgrType_T.MUTI)) {
            // 场景下只允许一个UI，从场景下获取节点
            node = CanvasExt.getNode(uiType, parent);
        }

        if ((!node || !node.isValid) && !!(mType & UIMgrType_T.POOL)) {
            // 指定对象池获取
            node = this.getPool(uiType).get();
            if (node)
                parent.addChild(node);
        }

        if ((!node || !node.isValid) && pfb)
            node = CanvasExt.addChild({
                node: pfb,
                uiType,
                parent
            });

        return node;
    }

}
